package com.yaojiaxun.logisticsPlatformSystem.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.yaojiaxun.logisticsPlatformSystem.dto.BuildInfoDTO;
import com.yaojiaxun.logisticsPlatformSystem.dto.PageDTO;
import com.yaojiaxun.logisticsPlatformSystem.entity.BuildInfo;
import com.yaojiaxun.logisticsPlatformSystem.mapper.BuildInfoMapper;
import com.yaojiaxun.logisticsPlatformSystem.util.SnowFlakeIDWorker;
import com.yaojiaxun.logisticsPlatformSystem.util.TimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: yjx_j
 * @Date: 2019/1/23 10:59
 * @Description:
 */
@Service
public class BuildInfoService {

    @Autowired
    private BuildInfoMapper buildInfoMapper;

    public Boolean addBuildInfo(BuildInfo buildInfo){
        buildInfo.setBuildId(new SnowFlakeIDWorker(4,1).nextId());
        buildInfo.setCreateTime(Instant.now().toEpochMilli());
        buildInfo.setUpdateTime(Instant.now().toEpochMilli());
        return buildInfoMapper.addBuildInfo(buildInfo)>0;
    }

    public Boolean deleteBuildInfoById(Long buildId){
        return buildInfoMapper.deleteBuildInfoById(buildId)>0;
    }

    public BuildInfo findBuildInfoById(Long buildId){
        return buildInfoMapper.selectBuildById(buildId);
    }

    public Boolean updateBuildInfo(BuildInfo buildInfo){
        buildInfo.setUpdateTime(Instant.now().toEpochMilli());
        return buildInfoMapper.updateBuildInfo(buildInfo)>0;
    }

    public BuildInfoDTO beanToDTO(BuildInfo buildInfo){
        if (buildInfo == null)
            return null;
        BuildInfoDTO buildInfoDTO = new BuildInfoDTO();
        BeanUtils.copyProperties(buildInfo, buildInfoDTO);
        buildInfoDTO.setCreateTime(TimeFormat.convertTime(buildInfo.getCreateTime()));
        buildInfoDTO.setUpdateTime(TimeFormat.convertTime(buildInfo.getUpdateTime()));
        return buildInfoDTO;
    }

    public PageDTO<BuildInfoDTO> findPage(Integer pageNum){
        PageDTO<BuildInfoDTO> pageDTO = new PageDTO<>();
        Page<BuildInfoDTO> page = new Page<>(pageNum, 10);
        List<BuildInfoDTO> results = buildInfoMapper.selectPage(page, null).stream().map(this::beanToDTO).collect(Collectors.toList());
        pageDTO.setResult(results);
        pageDTO.setPage(page);
        return pageDTO;

    }
}
